/**
 * 智融财务管理系统主布局组件 - 美团品牌风格的完整应用布局
 *
 * 开发人员：唐梓鑫
 * 开发时间：2025-10-20 至 2025-10-25
 * 模块职责：实现整个应用的主布局框架，包括侧边栏导航、顶栏面包屑、主内容区域等
 *
 * 技术要点：
 * - Vue2组件化开发，响应式布局设计
 * - 美团品牌色彩系统和视觉规范
 * - 侧边栏导航菜单和权限控制
 * - 面包屑导航和动态路由处理
 * - 用户信息展示和登出功能
 *
 * 开发故事：负责前端架构的核心布局设计，与后端认证系统深度集成，实现美团品牌风格的完整用户界面框架。
 */
<template>
  <div class="layout">
    <!-- 侧边栏 -->
    <aside class="sider" v-if="!isLoginPage">
      <div class="logo">
        <img src="@/assets/images/美团图标.png" alt="Logo" class="logo-icon" />
        <span>智融财务</span>
      </div>
      <el-menu :default-active="active" class="menu" router>
        <el-menu-item 
          v-for="menu in visibleMenus"
          :key="menu.path"
          :index="menu.path"
        >
          <i :class="menu.icon"></i>
          <span>{{menu.name}}</span>
        </el-menu-item>
      </el-menu>
      <div class="sider-footer">
        <div class="user-info">
          <el-avatar :size="32" icon="el-icon-user-solid" :style="{background: 'var(--primary-color)', color: 'var(--text-primary)'}"></el-avatar>
          <div class="user-text">
            <div class="user-name">{{username}}</div>
            <div class="user-role">管理员</div>
          </div>
        </div>
        <el-button type="text" icon="el-icon-switch-button" @click="logout" style="color: var(--text-tertiary)"></el-button>
      </div>
    </aside>
    
    <!-- 主内容区 -->
    <main class="main" :class="{ full: isLoginPage }">
      <!-- 顶栏 -->
      <header class="topbar" v-if="!isLoginPage">
        <div class="topbar-left">
          <el-breadcrumb separator="/" class="breadcrumb-nav">
            <el-breadcrumb-item :to="{ path: '/dashboard' }" class="breadcrumb-home">
              <i class="el-icon-house"></i>
              <span>首页</span>
            </el-breadcrumb-item>
            <el-breadcrumb-item 
              v-for="(item, index) in breadcrumbItems" 
              :key="index"
              :to="item.path ? { path: item.path } : null"
              class="breadcrumb-page"
            >
              <i :class="item.icon" v-if="item.icon"></i>
              <span>{{item.title}}</span>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="topbar-right">
          <div class="enterprise-info">
            <i class="el-icon-office-building"></i>
            <span>{{enterpriseName}}</span>
          </div>
          <div class="user-info">
            <el-avatar :size="32" icon="el-icon-user-solid" class="user-avatar"></el-avatar>
            <span class="user-name">{{username}}</span>
          </div>
        </div>
      </header>
      
      <!-- 路由视图 -->
      <div class="content" :class="{ 'no-padding': isLoginPage }">
    <router-view />
      </div>
    </main>
  </div>
</template>

<script>
import http from '../api/http'

export default {
  data(){
    return { 
      active: this.$route.path,
      username: localStorage.getItem('username') || 'User',
      enterpriseName: localStorage.getItem('enterpriseName') || 'Demo Enterprise',
      permissions: [],
      visibleMenus: []
    }
  },
  async created() {
    await this.loadUserMenus()
  },
  computed: {
    isLoginPage(){ return this.$route.path === '/login' },
    pageTitle(){
      const titles = {
        '/dashboard': '数据看板',
        '/payments': '支付管理',
        '/products': '产品管理',
        '/financing': '融资服务',
        '/reports': '报表AI',
        '/enterprises': '企业管理',
        '/users': '用户管理'
      }
      return titles[this.$route.path] || ''
    },
    breadcrumbItems() {
      const route = this.$route.path
      const items = []
      
      // 根据当前路由生成面包屑
      if (route === '/dashboard') {
        // 首页不需要额外的面包屑
        return []
      } else if (route === '/payments') {
        items.push({ title: '支付管理', icon: 'el-icon-wallet', path: '/payments' })
      } else if (route === '/products') {
        items.push({ title: '产品管理', icon: 'el-icon-goods', path: '/products' })
      } else if (route === '/financing') {
        items.push({ title: '融资服务', icon: 'el-icon-money', path: '/financing' })
      } else if (route === '/reports') {
        items.push({ title: '报表AI', icon: 'el-icon-document', path: '/reports' })
      } else if (route === '/enterprises') {
        items.push({ title: '企业管理', icon: 'el-icon-office-building', path: '/enterprises' })
      } else if (route === '/users') {
        items.push({ title: '用户管理', icon: 'el-icon-user', path: '/users' })
      }
      
      return items
    }
  },
  watch: {
    '$route.path'(p){ this.active = p }
  },
  mounted(){
    // 获取企业信息
    const eid = localStorage.getItem('enterpriseId')
    if(eid && !this.isLoginPage){
      this.loadEnterpriseInfo(eid)
    }
  },
  methods: {
    async loadUserMenus() {
      if (this.isLoginPage) return
      
      try {
        const enterpriseId = localStorage.getItem('enterpriseId') || 1
        const userId = localStorage.getItem('userId') || 1
        const { data } = await http.get(`/enterprises/${enterpriseId}/users/${userId}/menus`)
        
        if (data.code === 0 && data.data) {
          this.permissions = data.data.permissions || []
          this.visibleMenus = data.data.menus || []
          // 保存权限到localStorage供其他组件使用
          localStorage.setItem('permissions', JSON.stringify(this.permissions))
        } else {
          // 如果API失败，使用默认菜单
          this.setDefaultMenus()
        }
      } catch (e) {
        console.error('加载菜单失败', e)
        // API失败时使用默认菜单
        this.setDefaultMenus()
      }
    },
    
    setDefaultMenus() {
      // 默认显示所有菜单（向后兼容）
      this.visibleMenus = [
        { name: '数据看板', path: '/dashboard', icon: 'el-icon-data-analysis' },
        { name: '支付管理', path: '/payments', icon: 'el-icon-wallet' },
        { name: '产品管理', path: '/products', icon: 'el-icon-goods' },
        { name: '融资服务', path: '/financing', icon: 'el-icon-money' },
        { name: '报表AI', path: '/reports', icon: 'el-icon-document' },
        { name: '企业管理', path: '/enterprises', icon: 'el-icon-office-building' },
        { name: '用户管理', path: '/users', icon: 'el-icon-user' }
      ]
    },
    
    async loadEnterpriseInfo(id){
      try {
        const { data } = await http.get(`/enterprises/${id}`)
        if(data.code === 0){
          this.enterpriseName = data.data.name
          localStorage.setItem('enterpriseName', data.data.name)
        }
      } catch(e) {
        console.error('Failed to load enterprise info', e)
      }
    },
    logout(){
      this.$confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.removeItem('token')
        localStorage.removeItem('username')
        localStorage.removeItem('enterpriseId')
        localStorage.removeItem('userId')
        localStorage.removeItem('enterpriseName')
        localStorage.removeItem('permissions')
        this.$router.push('/login')
        this.$message.success('已退出登录')
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.layout { 
  display: flex; 
  min-height: 100vh; 
  background: var(--bg-page);
  position: relative;
}

.layout::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 20% 80%, rgba(255, 209, 0, 0.08) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(6, 192, 95, 0.08) 0%, transparent 50%);
  pointer-events: none;
  z-index: -1;
}

.sider { 
  width: var(--sider-width); 
  background: var(--sider-gradient);
  box-shadow: var(--sider-shadow);
  display: flex;
  flex-direction: column;
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  z-index: 100;
  transition: all var(--transition-normal);
  border-right: 1px solid var(--border-primary);
}

.sider:hover {
  box-shadow: 0 0 32px rgba(255, 209, 0, 0.15);
}

.logo { 
  height: 72px; 
  display: flex; 
  align-items: center; 
  justify-content: center;
  font-weight: 800;
  font-size: 20px;
  color: var(--text-primary); 
  background: var(--sider-gradient);
  border-bottom: 2px solid var(--border-primary);
  gap: 12px;
  position: relative;
  transition: all var(--transition-normal);
}

.logo::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 2px;
  background: var(--primary-gradient);
  border-radius: 1px;
  opacity: 0;
  transition: opacity var(--transition-normal);
}

.sider:hover .logo::after {
  opacity: 1;
}

.logo-icon {
  height: 36px;
  width: auto;
  transition: all var(--transition-normal);
  filter: drop-shadow(0 2px 4px rgba(255, 209, 0, 0.3));
}

.sider:hover .logo-icon {
  transform: scale(1.05);
  filter: drop-shadow(0 4px 8px rgba(255, 209, 0, 0.4));
}

.menu { 
  flex: 1;
  border-right: none;
  padding: 16px 0;
  animation: slideInLeft 0.6s ease-out;
}

.sider-footer {
  padding: 20px;
  border-top: 2px solid var(--border-primary);
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: var(--bg-primary);
  transition: all var(--transition-normal);
}

.sider-footer:hover {
  background: white;
  border-top-color: var(--primary-color);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  transition: all var(--transition-normal);
}

.user-info:hover {
  transform: translateX(4px);
}

.user-text {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-size: 14px;
  font-weight: 700;
  color: var(--text-primary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  transition: color var(--transition-normal);
}

.user-role {
  font-size: 12px;
  color: var(--text-secondary);
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.main {
  flex: 1;
  margin-left: var(--sider-width);
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  transition: all var(--transition-normal);
}

.main.full { 
  margin-left: 0; 
}

.topbar {
  height: 64px;
  background: linear-gradient(135deg, #ffffff 0%, #fafafa 100%);
  border-bottom: 1px solid var(--border-primary);
  padding: 0 var(--space-lg);
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  position: relative;
  z-index: 100;
  transition: all var(--transition-normal);
}

.topbar-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.topbar-right {
  display: flex;
  align-items: center;
  gap: var(--space-lg);
}

.enterprise-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: var(--bg-primary);
  border-radius: var(--radius-lg);
  border: 1px solid var(--border-primary);
  font-size: 14px;
  color: var(--text-secondary);
  font-weight: 600;
  transition: all var(--transition-normal);
}

.enterprise-info:hover {
  background: var(--primary-gradient);
  color: var(--text-primary);
  transform: translateY(-1px);
  box-shadow: var(--primary-shadow);
}

.enterprise-info i {
  color: var(--primary-color);
  transition: all var(--transition-normal);
}

.enterprise-info:hover i {
  color: var(--text-primary);
  transform: scale(1.1);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 16px;
  background: var(--bg-primary);
  border-radius: var(--radius-lg);
  border: 1px solid var(--border-primary);
  transition: all var(--transition-normal);
}

.user-info:hover {
  background: var(--primary-gradient);
  transform: translateY(-1px);
  box-shadow: var(--primary-shadow);
}

.user-avatar {
  background: var(--primary-gradient) !important;
  color: var(--text-primary) !important;
  transition: all var(--transition-normal);
}

.user-info:hover .user-avatar {
  transform: scale(1.1);
  box-shadow: var(--primary-shadow);
}

.user-name {
  font-size: 14px;
  color: var(--text-secondary);
  font-weight: 600;
  transition: all var(--transition-normal);
}

.user-info:hover .user-name {
  color: var(--text-primary);
}

.content {
  flex: 1;
  padding: var(--space-lg);
  overflow-y: auto;
  animation: fadeInUp 0.8s ease-out;
  position: relative;
}

.content.no-padding { 
  padding: 0; 
}

/* 面包屑样式优化 */
.breadcrumb-nav {
  display: flex;
  align-items: center;
  gap: 0;
  flex-wrap: nowrap;
  white-space: nowrap;
}

:deep(.el-breadcrumb) {
  font-size: 14px;
  line-height: 1.5;
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  white-space: nowrap;
}

:deep(.el-breadcrumb__item) {
  font-weight: 500;
  transition: all var(--transition-normal);
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

:deep(.el-breadcrumb__item .el-breadcrumb__inner) {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border-radius: var(--radius-md);
  transition: all var(--transition-normal);
  text-decoration: none;
  color: var(--text-secondary);
  font-size: 14px;
  white-space: nowrap;
}

.breadcrumb-home :deep(.el-breadcrumb__inner) {
  color: var(--text-primary);
  background: var(--primary-gradient);
  font-weight: 600;
  box-shadow: var(--primary-shadow);
}

.breadcrumb-home :deep(.el-breadcrumb__inner:hover) {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(255, 209, 0, 0.4);
}

.breadcrumb-page :deep(.el-breadcrumb__inner) {
  color: var(--text-secondary);
  background: var(--bg-primary);
  border: 1px solid var(--border-primary);
}

.breadcrumb-page :deep(.el-breadcrumb__inner:hover) {
  background: var(--primary-gradient);
  color: var(--text-primary);
  transform: translateY(-1px);
  box-shadow: var(--primary-shadow);
  border-color: var(--primary-color);
}

:deep(.el-breadcrumb__separator) {
  color: var(--text-tertiary);
  margin: 0 8px;
  font-weight: 600;
  font-size: 12px;
  flex-shrink: 0;
  display: inline-block;
}

/* 退出按钮样式 */
:deep(.el-button--text) {
  color: var(--text-tertiary);
  transition: all var(--transition-normal);
  border-radius: var(--radius-md);
  padding: 8px;
}

:deep(.el-button--text:hover) {
  color: var(--error-color);
  background: #ffe6e6;
  transform: scale(1.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sider {
    transform: translateX(-100%);
    transition: transform var(--transition-normal);
  }
  
  .sider.mobile-open {
    transform: translateX(0);
  }
  
  .main {
    margin-left: 0;
  }
  
  .content {
    padding: 16px;
  }
  
  .topbar {
    padding: 16px 20px;
  }
}

/* 滚动条样式 */
:deep(.el-menu) {
  scrollbar-width: thin;
  scrollbar-color: var(--primary-color) transparent;
}

:deep(.el-menu::-webkit-scrollbar) {
  width: 6px;
}

:deep(.el-menu::-webkit-scrollbar-track) {
  background: transparent;
}

:deep(.el-menu::-webkit-scrollbar-thumb) {
  background: var(--primary-color);
  border-radius: 3px;
}

:deep(.el-menu::-webkit-scrollbar-thumb:hover) {
  background: var(--primary-dark);
}
</style>

